#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :user_role_permission_page.py
# Time  :2025/4/22 10:32
# Email :fortunatedong@163.com
# Author:by Adonli
import os

import streamlit as st
import toml

from config import ROOT_DIR
from settings.user_role_permission import load_users, save_users
from config import Header_space

Header_space()
st.subheader("用户权限设置", divider=True)
users_role_permission = load_users()
tab1, tab2, tab3 = st.tabs(["**角色管理**", "**权限管理**", "**用户管理**"])

with tab1:
    # 定义下拉选项
    rolecode_options = list(set([user["rolecode"] for user in users_role_permission["ROLES"]]))
    rolename_options = list(set([user["rolename"] for user in users_role_permission["ROLES"]]))
    delete_rolename_options = [user["rolename"] for user in users_role_permission["ROLES"]]
    role_datas_result = users_role_permission["ROLES"]


    def search(users_data, rolecode=None, rolename=None):
        rolecode = rolecode if rolecode else None
        rolename = rolename if rolename else None

        role_datas_result = {"ROLES": []}
        filtered_roles = users_data.copy()

        if rolecode is not None:
            userid_exists = any(rolecode in role['rolecode'] for role in filtered_roles)
            if not userid_exists:
                return f"rolecode不存在这个参数: {rolecode}"
            filtered_roles = [role for role in filtered_roles if rolecode in role['rolecode']]

        if rolename is not None:
            rolename_exists = any(rolename in role['rolename'] for role in filtered_roles)
            if not rolename_exists:
                return f"rolename不存在这个参数: {rolename}"
            filtered_roles = [role for role in filtered_roles if rolename in role['rolename']]

        role_datas_result["ROLES"] = filtered_roles
        return role_datas_result["ROLES"]


    col1, col2, col3, col4 = st.columns(4)
    with col1:
        rolecode = st.text_input(":blossom:**角色策略编码**", key="tab1_rolecode")
    with col3:
        rolename = st.text_input(":blossom:**角色策略**", key="tab1_rolename")
    with col4:
        col4_col1, col4_col2, col4_col3, col4_col4, col4_col5 = st.columns(5)
        with col4_col2:
            st.write("")
            search_button = st.button("**搜索**", key="tab1_search_button")
            if search_button:
                role_datas_result = search(users_role_permission["ROLES"], rolecode, rolename)

        with col4_col3:
            st.write("")
            add_role_button = st.button("**新增**", key="tab1_add_role_button")


            @st.dialog("新增一个角色")
            def vote():
                st.write(f"创建角色时需配置好角色策略")
                add_rolecode = st.text_input(":blossom:**角色策略编码**", key="tab1_add_rolecode")
                if add_rolecode in rolecode_options:
                    st.warning("角色策略编码重复，重写设置角色策略编码")
                add_rolename = st.text_input(":blossom:**角色策略**", key="tab1_add_rolename")
                if st.button("确定"):
                    add_role = {"rolecode": add_rolecode, "rolename": add_rolename}
                    users_role_permission["ROLES"].append(add_role)
                    save_users(users_role_permission)
                    st.rerun()


            if add_role_button:
                vote()

        with col4_col4:
            st.write("")
            edit_button = st.button("**修改**", key="tab1_edit_button")


            @st.dialog("修改角色信息")
            def edit_role():
                selected_role = st.selectbox("选择要修改的角色",
                                             [f"{role['rolecode']} - {role['rolename']}" for role in
                                              users_role_permission["ROLES"]],
                                             index=None,
                                             placeholder="选择角色...")

                if selected_role:
                    selected_rolecode = selected_role.split(" - ")[0]
                    role_to_edit = next(
                        (role for role in users_role_permission["ROLES"] if role["rolecode"] == selected_rolecode),
                        None)

                    if role_to_edit:
                        new_rolecode = st.text_input(":blossom:**新角色策略编码**", value=role_to_edit["rolecode"])
                        new_rolename = st.text_input(":blossom:**新角色策略**", value=role_to_edit["rolename"])

                        if st.button("确认修改"):
                            role_to_edit["rolecode"] = new_rolecode
                            role_to_edit["rolename"] = new_rolename
                            save_users(users_role_permission)
                            st.rerun()


            if edit_button:
                edit_role()

        with col4_col5:
            st.write("")
            delete_button = st.button("**删除**", key="tab1_delete_button")


            @st.dialog("删除一个角色")
            def vote():
                rolename = st.selectbox(":blossom:**角色策略名字**",
                                        delete_rolename_options,
                                        index=None,
                                        placeholder="选择角色策略...")
                if st.button("确定"):
                    users_role_permission["ROLES"] = [
                        user for user in users_role_permission["ROLES"]
                        if user["rolename"] != rolename
                    ]
                    save_users(users_role_permission)
                    st.rerun()


            if delete_button:
                vote()

    st.dataframe(role_datas_result)

with tab2:
    rolecode_options = list(set([user["rolecode"] for user in users_role_permission["PERMISSIONPAGE"]]))
    delete_rolecode_options = [user["rolename"] for user in users_role_permission["PERMISSIONPAGE"]]
    rolename_options = list(set([user["rolename"] for user in users_role_permission["PERMISSIONPAGE"]]))
    add_rolecode_options = list(set([user["rolecode"] for user in users_role_permission["ROLES"]]))
    add_rolename_options = list(set([user["rolename"] for user in users_role_permission["ROLES"]]))
    configs_toml = os.path.join(ROOT_DIR, 'settings/configs.toml')
    with open(configs_toml, "r", encoding="utf-8") as f:
        cfg = toml.load(f)
    permission_options_list = cfg['PAGES']['PAGES_NAVIGATION_LIST']
    permission_datas_result = users_role_permission["PERMISSIONPAGE"]


    def search(users_data, rolecode=None, rolename=None):
        rolecode = rolecode if rolecode else None
        rolename = rolename if rolename else None

        permission_datas_result = {"PERMISSIONPAGE": []}
        filtered_roles = users_data.copy()

        if rolecode is not None:
            userid_exists = any(rolecode in role['rolecode'] for role in filtered_roles)
            if not userid_exists:
                return f"rolecode不存在这个参数: {rolecode}"
            filtered_roles = [role for role in filtered_roles if rolecode in role['rolecode']]

        if rolename is not None:
            rolename_exists = any(rolename in role['rolename'] for role in filtered_roles)
            if not rolename_exists:
                return f"rolename不存在这个参数: {rolename}"
            filtered_roles = [role for role in filtered_roles if rolename in role['rolename']]

        permission_datas_result["PERMISSIONPAGE"] = filtered_roles
        return permission_datas_result["PERMISSIONPAGE"]


    col1, col2, col3, col4 = st.columns(4)
    with col1:
        rolecode = st.text_input(":blossom:**角色策略编码**", key="tab2_rolecode")
    with col3:
        rolename = st.text_input(":blossom:**角色策略**", key="tab2_rolename")
    with col4:
        col4_col1, col4_col2, col4_col3, col4_col4, col4_col5 = st.columns(5)
        with col4_col2:
            st.write("")
            search_button = st.button("**搜索**", key="tab2_search_button")
            if search_button:
                permission_datas_result = search(users_role_permission["PERMISSIONPAGE"], rolecode, rolename)

        with col4_col3:
            st.write("")
            add_permission_button = st.button("**新增**", key="tab2_add_permission_button")


            @st.dialog("新增一个角色权限")
            def vote():
                st.write(f"创建角色权限时需配置好角色策略")
                add_rolecode = st.selectbox(":blossom:**角色策略编码**",
                                            add_rolecode_options,
                                            index=None,
                                            placeholder="选择部门...")
                add_rolename = st.selectbox(":blossom:**角色策略**",
                                            add_rolename_options,
                                            index=None,
                                            placeholder="选择部门...")
                add_permission = st.multiselect(":blossom:**选择功能模块**",
                                                permission_options_list,
                                                placeholder="选择功能...")
                if st.button("确定"):
                    add_role = {"rolecode": add_rolecode, "rolename": add_rolename, "permission": add_permission}
                    users_role_permission["PERMISSIONPAGE"].append(add_role)
                    save_users(users_role_permission)
                    st.rerun()


            if add_permission_button:
                vote()

        with col4_col4:
            st.write("")
            edit_button = st.button("**修改**", key="tab2_edit_button")


            @st.dialog("修改权限信息")
            def edit_permission():
                selected_permission = st.selectbox("选择要修改的权限",
                                                   [f"{perm['rolecode']} - {perm['rolename']}" for perm in
                                                    users_role_permission["PERMISSIONPAGE"]],
                                                   index=None,
                                                   placeholder="选择权限...")

                if selected_permission:
                    selected_rolecode = selected_permission.split(" - ")[0]
                    perm_to_edit = next((perm for perm in users_role_permission["PERMISSIONPAGE"] if
                                         perm["rolecode"] == selected_rolecode), None)

                    if perm_to_edit:
                        new_rolecode = st.text_input(":blossom:**新角色策略编码**", value=perm_to_edit["rolecode"])
                        new_rolename = st.text_input(":blossom:**新角色策略**", value=perm_to_edit["rolename"])
                        new_permission = st.multiselect(":blossom:**新功能模块**",
                                                        permission_options_list,
                                                        default=perm_to_edit["permission"])

                        if st.button("确认修改"):
                            perm_to_edit["rolecode"] = new_rolecode
                            perm_to_edit["rolename"] = new_rolename
                            perm_to_edit["permission"] = new_permission
                            save_users(users_role_permission)
                            st.rerun()


            if edit_button:
                edit_permission()

        with col4_col5:
            st.write("")
            delete_button = st.button("**删除**", key="tab2_delete_button")


            @st.dialog("删除一个权限")
            def vote():
                rolename = st.selectbox(":blossom:**角色策略名字**",
                                        delete_rolecode_options,
                                        index=None,
                                        placeholder="选择角色策略...")
                if st.button("确定"):
                    users_role_permission["PERMISSIONPAGE"] = [
                        user for user in users_role_permission["PERMISSIONPAGE"]
                        if user["rolename"] != rolename
                    ]
                    save_users(users_role_permission)
                    st.rerun()


            if delete_button:
                vote()

    st.dataframe(permission_datas_result)

with tab3:
    userid_options = list(set([user["userid"] for user in users_role_permission["USERS"]]))
    delete_userid_options = [user["userid"] for user in users_role_permission["USERS"]]
    department_options = list(set([user["department"] for user in users_role_permission["USERS"]]))
    rolecode_options = list(set([user["rolecode"] for user in users_role_permission["USERS"]]))
    rolename_options = list(set([user["rolename"] for user in users_role_permission["USERS"]]))
    add_rolecode_options = list(set([user["rolecode"] for user in users_role_permission["ROLES"]]))
    add_rolename_options = list(set([user["rolename"] for user in users_role_permission["ROLES"]]))

    user_datas_result = users_role_permission["USERS"]


    def search(users_data, userid=None, department=None, rolename=None):
        userid = userid if userid else None
        department = department if department else None
        rolename = rolename if rolename else None

        user_datas_result = {"USERS": []}
        filtered_users = users_data.copy()

        if userid is not None:
            userid_exists = any(userid in user['userid'] for user in filtered_users)
            if not userid_exists:
                return f"userid不存在这个参数: {userid}"
            filtered_users = [user for user in filtered_users if userid in user['userid']]

        if department is not None:
            department_exists = any(department in user['department'] for user in filtered_users)
            if not department_exists:
                return f"department不存在这个参数: {department}"
            filtered_users = [user for user in filtered_users if department in user['department']]

        if rolename is not None:
            rolename_exists = any(rolename in user['rolename'] for user in filtered_users)
            if not rolename_exists:
                return f"rolename不存在这个参数: {rolename}"
            filtered_users = [user for user in filtered_users if rolename in user['rolename']]

        user_datas_result["USERS"] = filtered_users
        return user_datas_result["USERS"]


    col1, col2, col3, col4 = st.columns(4)
    with col1:
        userid = st.text_input(":blossom:**账号**")
    with col2:
        department = st.text_input(":blossom:**部门**")
    with col3:
        rolename = st.text_input(":blossom:**角色策略**")
    with col4:
        col4_col1, col4_col2, col4_col3, col4_col4, col4_col5 = st.columns(5)
        with col4_col2:
            st.write("")
            search_button = st.button("**搜索**")
            if search_button:
                user_datas_result = search(users_role_permission["USERS"], userid, department, rolename)

        with col4_col3:
            st.write("")
            add_button = st.button("**新增**")


            @st.dialog("新增一个账户")
            def vote():
                st.write(f"创建账户时需配置好角色策略")
                userid = st.text_input(":blossom:**账号**", key="add_userid")
                if userid in userid_options:
                    st.warning("用户名重复，重写设置用户名")
                password = st.text_input(":blossom:**密码**", key="add_password")
                department = st.text_input(":blossom:**部门**", key="add_department")
                rolecode = st.selectbox(":blossom:**角色策略编码**",
                                        add_rolecode_options,
                                        index=None,
                                        placeholder="选择角色策略编码...")
                rolename = st.selectbox(":blossom:**角色策略**",
                                        add_rolename_options,
                                        index=None,
                                        placeholder="选择角色策略...")
                if st.button("确定"):
                    add_user = {"userid": userid, "password": password, "department": department,
                                "rolecode": rolecode, "rolename": rolename}
                    users_role_permission["USERS"].append(add_user)
                    save_users(users_role_permission)
                    st.rerun()


            if add_button:
                vote()

        with col4_col4:
            st.write("")
            edit_button = st.button("**修改**")


            @st.dialog("修改用户信息")
            def edit_user():
                selected_user = st.selectbox("选择要修改的用户",
                                             [f"{user['userid']} - {user['department']}" for user in
                                              users_role_permission["USERS"]],
                                             index=None,
                                             placeholder="选择用户...")

                if selected_user:
                    selected_userid = selected_user.split(" - ")[0]
                    user_to_edit = next(
                        (user for user in users_role_permission["USERS"] if user["userid"] == selected_userid), None)

                    if user_to_edit:
                        new_userid = st.text_input(":blossom:**新账号**", value=user_to_edit["userid"])
                        new_password = st.text_input(":blossom:**新密码**", value=user_to_edit["password"])
                        new_department = st.text_input(":blossom:**新部门**", value=user_to_edit["department"])
                        new_rolecode = st.selectbox(":blossom:**新角色策略编码**",
                                                    add_rolecode_options,
                                                    index=add_rolecode_options.index(user_to_edit["rolecode"]) if
                                                    user_to_edit["rolecode"] in add_rolecode_options else 0)
                        new_rolename = st.selectbox(":blossom:**新角色策略**",
                                                    add_rolename_options,
                                                    index=add_rolename_options.index(user_to_edit["rolename"]) if
                                                    user_to_edit["rolename"] in add_rolename_options else 0)

                        if st.button("确认修改"):
                            user_to_edit["userid"] = new_userid
                            user_to_edit["password"] = new_password
                            user_to_edit["department"] = new_department
                            user_to_edit["rolecode"] = new_rolecode
                            user_to_edit["rolename"] = new_rolename
                            save_users(users_role_permission)
                            st.rerun()


            if edit_button:
                edit_user()

        with col4_col5:
            st.write("")
            delete_button = st.button("**删除**")


            @st.dialog("删除一个账户")
            def vote():
                userid = st.selectbox(":blossom:**用户名**",
                                      delete_userid_options,
                                      index=None,
                                      placeholder="选择用户名...")
                if st.button("确定"):
                    users_role_permission["USERS"] = [
                        user for user in users_role_permission["USERS"]
                        if user["userid"] != userid
                    ]
                    save_users(users_role_permission)
                    st.rerun()


            if delete_button:
                vote()

    edited_data = st.dataframe(user_datas_result)